/**
 * @(#)DianpingService.java, 2013-2-12. Copyright 2013 RENREN, Inc. All rights
 *                           reserved. RENREN PROPRIETARY/CONFIDENTIAL. Use is
 *                           subject to license terms.
 */
package com.wennimei.service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.annotation.PostConstruct;

import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.wennimei.util.DataUtil;
import com.wennimei.util.FileProcessor;
import com.wennimei.util.FileUtil;
import com.wennimei.util.HttpUtil;
import com.wennimei.util.MemcachedUtil;
import com.wennimei.util.ShortUrlUtil;

/**
 * @author shichen.feng@renren-inc.com
 */
@Service
public class DianpingService {

    private static final Set<String> typeMap = new HashSet<String>();

    private static final Set<String> cityMap = new HashSet<String>();

    @PostConstruct
    void init() {
        FileUtil.processFile(DataUtil.BUSINESS_CATEGORY, new FileProcessor() {

            @Override
            public void process(String line) {
                typeMap.add(line);
            }
        });

        FileUtil.processFile(DataUtil.BUSINESS_CITY, new FileProcessor() {

            @Override
            public void process(String line) {
                String[] array = line.split(",");
                for (String s: array) {
                    cityMap.add(s);
                }
            }
        });
    }

    @SuppressWarnings("unchecked")
    public String findBusiness(String latitude, String longitude) {
        // 定义申请获得的appKey和appSecret
        String appkey = "4548067847";
        String secret = "2217877caa2e40ca85eb7b5079e9f3b3";
        String apiUrl = "http://api.dianping.com/v1/business/find_businesses";

        // 创建参数表
        Map<String, String> paramMap = new HashMap<String, String>();
        {
            paramMap.put("latitude", latitude);
            paramMap.put("longitude", longitude);
            paramMap.put("radius", "2000");
            paramMap.put("limit", "10");
            paramMap.put("category", "美食");
            paramMap.put("sort", "7");
        }
        // 对参数名进行字典排序
        String[] keyArray = paramMap.keySet().toArray(new String[0]);
        Arrays.sort(keyArray);

        // 拼接有序的参数名-值串
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(appkey);
        for (String key: keyArray) {
            stringBuilder.append(key).append(paramMap.get(key));
        }

        stringBuilder.append(secret);
        String codes = stringBuilder.toString();

        String sign = org.apache.commons.codec.digest.DigestUtils.shaHex(codes)
                .toUpperCase();

        // 使用签名生成访问URL
        stringBuilder = new StringBuilder();
        stringBuilder.append("appkey=").append(appkey).append("&sign=")
                .append(sign);
        for (Map.Entry<String, String> entry: paramMap.entrySet()) {
            stringBuilder.append('&').append(entry.getKey()).append('=')
                    .append(this.getEncode(entry.getKey(), entry.getValue()));
        }

        String requestUrl = apiUrl + "?" + stringBuilder.toString();
        String json = HttpUtil.get(requestUrl);
        if (null == json)
            return null;
        Gson gson = new Gson();
        Map<String, Object> res = gson.fromJson(json,
                new TypeToken<Map<String, Object>>() {}.getType());
        ArrayList<Map<String, Object>> list = (ArrayList<Map<String, Object>>) res
                .get("businesses");
        int i = 1;
        StringBuilder sb = new StringBuilder();
        for (Map<String, Object> b: list) {
            sb.append(i + "、" + b.get("name") + ",")
                    .append(b.get("branch_name") + ",")
                    .append(b.get("address") + ",")
                    .append(b.get("telephone") + ",")
                    .append(b.get("categories") + ",")
                    .append("距离" + b.get("distance") + "m\r\n")
                    .append("详情："
                            + ShortUrlUtil
                                    .getShortUrl("http://m.dianping.com/shop/"
                                            + ((Double) b.get("business_id"))
                                                    .intValue()) + "\r\n");
            i++;
        }
        return sb.append("本信息来自《大众点评网》").toString();
    }

    public String findBusinessReview(String businessId) {
        businessId = businessId.replace("大众点评", "");
        return "很好";
    }

    private String getEncode(String key, String value) {
        if (key.equals("city") || key.equals("category"))
            try {
                return URLEncoder.encode(value, "UTF8");
            } catch (UnsupportedEncodingException e) {
                return value;
            }

        return value;
    }

    public static boolean isInCache(String fromUserName) {
        return null != MemcachedUtil.getInstance().get("dp_" + fromUserName);
    }
}
